import router from '@/router'
import store from '@/store'

// 导航守卫
router.beforeEach(async(to, from, next) => {
  // 判断是否登录
  if (store.getters.token) {
    // 有token 的时候如果是去登录页 则让他跳到首页
    if (to.path === '/login') {
      next('/')
    } else {
      if (Object.keys(store.state.user.profile).length === 0) {
        await store.dispatch('user/getProfile')
        const menus = store.state.user.profile.roles.menus
        const res = await store.dispatch('permisson/filterRouter', menus)
        console.log(res)
        router.addRoutes([
          ...res,
          { path: '*', redirect: '/404', hidden: true }
        ])
        next(to.path)
      }
      next()
    }
  } else {
    // 判断一下是不是跳转到这三个页面 如果是的话就放行 不是的话就跳到登录页
    const pathList = ['/login', '/404', '/test']
    if (pathList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
    }
  }
})
